package com.chen.codesandbox.codeSandbox;

import com.chen.codesandbox.codeSandbox.Template.JavaCodeSandboxTemplate;
import com.chen.codesandbox.model.ExecuteMessage;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
import com.github.dockerjava.api.command.StatsCmd;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientImpl;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import com.github.dockerjava.httpclient5.ApacheDockerHttpClient;
import com.github.dockerjava.transport.DockerHttpClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import java.io.*;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.github.dockerjava.core.DefaultDockerClientConfig.*;

@Deprecated
//@Component
public class JavaDockerCodeSandboxOld extends JavaCodeSandboxTemplate {
    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";
    private Boolean FIRST_INIT = true;
    private static final long TIME_OUT = 3L;
    private boolean runTime = false;
    private String errorMessage;
    private String message;
    private long maxMemory;

    /**
     * 连接docker服务器
     *
     * @return
     */
    public DockerClient connect() {
        // 配置docker CLI的一些选项
        DefaultDockerClientConfig config = DefaultDockerClientConfig
                .createDefaultConfigBuilder()
                .withDockerTlsVerify(DOCKER_TLS_VERIFY)
                .withDockerHost("unix:///var/run/docker.sock")
                // 与docker版本对应，参考https://docs.docker.com/engine/api/#api-version-matrix
                // 或者通过docker version指令查看api version
                .withApiVersion(API_VERSION)
                .withRegistryUrl(REGISTRY_URL)
                .build();

        // 创建DockerHttpClient
        DockerHttpClient httpClient = new ApacheDockerHttpClient
                .Builder()
                .dockerHost(config.getDockerHost())
                .maxConnections(100)
                .connectionTimeout(Duration.ofSeconds(30))
                .responseTimeout(Duration.ofSeconds(45))
                .build();

        DockerClient dockerClient = DockerClientImpl.getInstance(config, httpClient);
        Info info = dockerClient.infoCmd().exec();
//        String infoStr = JSONObject.toJSONString(info);
        System.out.println("docker环境信息");
        System.out.println(info);
        return dockerClient;
    }

    @Override
    public List<ExecuteMessage> runFile(File userCodeFile, List<String> inputList) {
        String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();
        // 获取 Apache HttpClient 5 Docker Client
//        DockerClient dockerClient = DockerClientBuilder.getInstance().build();
        // 创建 HttpClient 5 的配置
        DockerClient dockerClient = connect();
        // 创建容器
        String image = "openjdk:8-alpine";
        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(image);
        HostConfig hostConfig = new HostConfig();
        hostConfig.withMemory(100 * 1000 * 1000L);
        hostConfig.withMemorySwap(0L);
        hostConfig.withCpuCount(1L);
//        hostConfig.withSecurityOpts(Arrays.asList("seccomp=安全管理配置字符串"));
        hostConfig.setBinds(new Bind(userCodeParentPath, new Volume("/app")));
        CreateContainerResponse createContainerResponse = containerCmd
                .withHostConfig(hostConfig)
                .withNetworkDisabled(true)
                .withReadonlyRootfs(true)
                .withAttachStdin(true)
                .withAttachStderr(true)
                .withAttachStdout(true)
                // 创建容器时设置 withTty(true)，TTY 模式会修改输入输出格式（如添加控制字符）。
                .withTty(true)
                .exec();
        System.out.println(createContainerResponse);
        String containerId = createContainerResponse.getId();

        // 启动容器
        dockerClient.startContainerCmd(containerId).exec();

        // docker exec keen_blackwell java -cp /app Main 1 3
        // 执行命令并获取结果
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String inputArgs : inputList) {
            StopWatch stopWatch = new StopWatch();
            String[] inputArgsArray = inputArgs.split(" ");
            String inputContent = String.join("\n", inputArgsArray) + "\n"; // 确保最后有换行
            System.out.println("inputArgsArray:" + Arrays.asList(inputArgsArray));
            InputStream inputStream = new ByteArrayInputStream(inputContent.getBytes());
            String[] cmdArray = new String[]{"java", "-cp", "/app", "Main"};
            ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(containerId)
                    .withCmd(cmdArray)
                    .withAttachStderr(true)
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .exec();
            System.out.println("创建执行命令：" + execCreateCmdResponse);

            ExecuteMessage executeMessage = new ExecuteMessage();
//            final String[] message = {null};
//            final String[] errorMessage = {null};
            long time = 0L;
            // 判断是否超时
//            boolean timeout = true;
            String execId = execCreateCmdResponse.getId();
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback() {
                @Override
                public void onComplete() {
                    // 如果执行完成，则表示没超时
                    runTime = false;
                    super.onComplete();
                }

                @Override
                public void onNext(Frame frame) {
                    StreamType streamType = frame.getStreamType();
                    if (StreamType.STDERR.equals(streamType)) {
                        errorMessage = new String(frame.getPayload());
                        errorMessage = StringUtils.chomp(errorMessage);
                        System.out.println("输出错误结果：" + errorMessage);
                    } else {
                        message = new String(frame.getPayload());
                        message = StringUtils.chomp(message);
                        System.out.println("输出结果：" + message);
                    }
                    super.onNext(frame);
                }
            };

//            final long[] maxMemory = {0L};

            // 获取占用的内存
//            maxMemory = 0;
            StatsCmd statsCmd = dockerClient.statsCmd(containerId);
            ResultCallback<Statistics> statisticsResultCallback = new ResultCallback<Statistics>() {

                private Closeable internalCloseable;

                @Override
                public void onNext(Statistics statistics) {
                    Long usageBytes = statistics.getMemoryStats().getUsage();
                    System.out.println("内存占用：" + usageBytes);
                    // statistics.getMemoryStats().getUsage()返回的是 字节（Bytes）。
                    // 转换为 KB (除以 1024)
                    maxMemory = Math.max(usageBytes / 1024, maxMemory);
                }

                @Override
                public void close() throws IOException {
                    if (internalCloseable != null) {
                        internalCloseable.close();
                        System.out.println("统计信息流已关闭");
                    }
                }

                @Override
                public void onStart(Closeable closeable) {
                    this.internalCloseable = closeable;
                }

                @Override
                public void onError(Throwable throwable) {
                    System.err.println("获取统计信息时出现错误：" + throwable.getMessage());
                    try {
                        close();
                    } catch (IOException e) {
                        System.out.println("关闭统计信息流时出错：" + e.getMessage());
                    }
                }

                @Override
                public void onComplete() {
                    // 打印最大内存使用量
                    System.out.println("最大内存占用：" + maxMemory);
                    try {
                        close();
                    } catch (IOException e) {
                        System.out.printf("打印最大内存使用量时错误：" + e.getMessage());
                    } finally {
                        maxMemory = 0;
                    }
                }
            };
            statsCmd.exec(statisticsResultCallback);
            try {
                stopWatch.start();
                dockerClient.execStartCmd(execId)
                        .withStdIn(inputStream)
                        .exec(execStartResultCallback)
                        .awaitCompletion(TIME_OUT, TimeUnit.SECONDS);
                stopWatch.stop();
                time = stopWatch.getLastTaskTimeMillis();
            } catch (InterruptedException e) {
                System.out.println("程序执行异常");
                throw new RuntimeException(e);
            } finally {
                try {
                    Thread.sleep(1500);
                    // 显式关闭流
                    statisticsResultCallback.close();
                    // 释放输入流
                    inputStream.close();
                } catch (IOException | InterruptedException e) {
                    System.out.println("关闭统计流时发生异常：" + e.getMessage());
                }
                // 执行完毕后强制删除容器，避免资源堆积
//                dockerClient.removeContainerCmd(containerId).withForce(true).exec();
                // 清理命令对象
                statsCmd.close();
            }

            executeMessage.setMessage(message);
            executeMessage.setErrorMessage(errorMessage);
            executeMessage.setTime(time);
            executeMessage.setMemory(maxMemory);
            executeMessageList.add(executeMessage);
        }
        System.out.println(executeMessageList);
        return executeMessageList;
    }
}